const service = require("../services/recipes");
const {BusinessError} = require("../common/util/error");
const getAll = async (req, res, next) => {
  try {
    const recipes = await service.getAll();
    res.json(recipes);
  } catch (err) {
    next(err);
  }
};
const save = async (req, res, next) => {
  try {
    const {
      name,
      healthLabels,
      cookTimeMinutes,
      prepTimeMinutes,
      ingredients,
    } = req.body;

    const newRecipe = {
      name,
      healthLabels: [...healthLabels],
      cookTimeMinutes,
      prepTimeMinutes,
      ingredients: [...ingredients],
    };
    // 201 Created
    res.status(201).json({ data: await service.save(newRecipe) });
  } catch (err) {
    next(err);
  }
};
const update = async (req, res, next) => {
  try{
    const {
      name,
      healthLabels,
      cookTimeMinutes,
      prepTimeMinutes,
      ingredients,
    } = req.body;
    const newRecipe = {
      name,
      healthLabels: [...healthLabels],
      cookTimeMinutes,
      prepTimeMinutes,
      ingredients: [...ingredients],
    };
    const updated = await service.update(req.params.id, newRecipe);
    res.json({ data: updated });
  }catch (e){
    next(e)
  }
};
const remove = async (req, res, next) => {
  try {
    await service.remove(req.params.id);
    res.status(204).end();
  } catch (err) {
    next(err);
  }
};
const get = async (req, res, next) => {
  try {
    res.json({ data: res.locals.recipe });
  }catch (e){
    next(e);
  }
};
// 在handler前提前进行查询
const recipesExists = async (req, res, next) => {
  const recipe = await service.get(req.params.id);
  if (!recipe) {
    const err =  new BusinessError({message: "Recipe not found", statusCode: 404});
    next(err);
  }else{
    // 请求生命周期内可用的之间数据
    res.locals.recipe = recipe;
    next();
  }
};
// 组合handler。需要提前查询的都由一个handler拦截了
module.exports = {
  getAll,
  save,
  update:[recipesExists,update],
  remove:[recipesExists,remove],
  get:[recipesExists,get] };
